/*
 * @Description:
 * @Version: V1.0.0
 * @Author: 周艳凯 484894717@qq.com
 * @Date: 2024-10-16 15:34:59
 * @LastEditors: 周艳凯 484894717@qq.com
 * @LastEditTime: 2024-10-17 15:39:55
 * @FilePath: gets.ts
 * Copyright 2024 Marvin, All Rights Reserved.
 * 2024-10-16 15:34:59
 */
import { isArray, isObject, isUndefined } from "@/utils/is";

export const getValueByPath = (obj, path) => {
  if (!obj || !path) {
    return void 0;
  }
  path = path.replace(/\[(\w+)\]/g, ".$1");
  const keys = path.split(".");
  if (keys.length === 0) {
    return void 0;
  }
  let temp = obj;
  for (let i = 0; i < keys.length; i++) {
    if ((!isObject(temp) && !isArray(temp)) || !keys[i]) {
      return void 0;
    }
    if (i !== keys.length - 1) {
      temp = temp[keys[i]];
    } else {
      return temp[keys[i]];
    }
  }
  return void 0;
};
export const setValueByPath = (obj, path, value, { addPath } = {}) => {
  console.log(obj, path, value, addPath, "我要巴啦啦了");
  if (!obj || !path) {
    return;
  }
  path = path.replace(/\[(\w+)\]/g, ".$1");
  const keys = path.split(".");
  if (keys.length === 0) {
    return;
  }
  let temp = obj;
  for (let i = 0; i < keys.length; i++) {
    if ((!isObject(temp) && !isArray(temp)) || !keys[i]) {
      return;
    }
    if (i !== keys.length - 1) {
      if (addPath && isUndefined(temp[keys[i]])) {
        temp[keys[i]] = {};
      }
      temp = temp[keys[i]];
    } else {
      temp[keys[i]] = value;
    }
  }
};
